package com.starblink.android.common.view.brand

import android.content.res.ColorStateList
import android.graphics.drawable.RotateDrawable
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.core.content.ContextCompat
import com.bumptech.glide.Glide
import com.guadou.lib_baselib.view.span.dsl.buildSpannableString
import com.starblink.android.basic.adapter.BaseBindingVH
import com.starblink.android.basic.adapter.BaseVH
import com.starblink.android.basic.aroute.CommonRoute
import com.starblink.android.basic.ext.color
import com.starblink.android.basic.ext.enableCorner
import com.starblink.android.basic.ext.inflater
import com.starblink.android.basic.ext.string
import com.starblink.android.basic.ext.visibleOrGone
import com.starblink.android.basic.extension.dp2px
import com.starblink.android.basic.extension.navigationTo
import com.starblink.android.basic.sensorsdata.extension.businessSuffixId
import com.starblink.android.basic.sensorsdata.extension.trackData
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.sensorsdata.spm.impl.SpmTrackHandler
import com.starblink.android.basic.util.FontUtil
import com.starblink.android.common.R
import com.starblink.android.common.databinding.CellSearchBrandBinding
import com.starblink.basic.ext.load
import com.starblink.basic.route.RoutePage
import com.starblink.rocketreserver.fragment.BrandVOF
import com.starblink.rocketreserver.fragment.ProductF

/**
 * 搜索-店铺结果-item
 */
class BrandResultCell(
    binding: CellSearchBrandBinding,
    recommended: Boolean = false,
    searchType: String = "normal",
    searchTerm: String = "",
    pageDef: Int = SpmPageDef.SearchBrandPage,
    private val onFollowClick: ((merchant: BrandVOF, position: Int) -> Unit)? = null
) :
    BaseBindingVH<BrandVOF, CellSearchBrandBinding>(binding) {

    private var pageDef: Int = 0
    var recommendIndex: Int = 0
    private var searchType: String = "normal"
    private var searchTerm: String = ""
    var recommended: Boolean = false

    init {
        this.pageDef = pageDef
//        this.recommendIndex = recommendIndex
        this.searchTerm = searchTerm
        this.searchType = searchType
        this.recommended = recommended

        val corner = 8.dp2px()

        binding.imgPrd1.enableCorner(corner)
        binding.imgPrd2.enableCorner(corner)
        binding.imgPrd3.enableCorner(corner)
        binding.imgPrd4.enableCorner(corner)

        binding.imgPrd1.borderRadius = corner.toFloat()
        binding.imgPrd2.borderRadius = corner.toFloat()
        binding.imgPrd3.borderRadius = corner.toFloat()
        binding.imgPrd4.borderRadius = corner.toFloat()

    }

    override fun onBind(merchat: BrandVOF, position: Int) {
        itemView.trackData(
            page = pageDef,
            element = SpmElementDef.Element_33014,
            params = mapOf(
                "brandName" to (merchat.name ?: ""),
                "index" to if (recommended) recommendIndex.toString() else position.toString(),
                "feedType" to if (recommended) "recommend" else "",
                "searchType" to searchType,
                "searchTerm" to searchTerm
            ),
            businessSuffixID = businessSuffixId(merchat)
        )

        binding.logo.load(merchat.logo, merchat.name)
        binding.bg.load(merchat.brandImg)
        binding.tvName.text = merchat.name
        binding.tvFollowers.visibleOrGone(merchat.subNums ?: 0 > 0) {
            text = "${merchat.subNums} Following"
        }
        if (merchat.spuNum != null && merchat.spuNum is Int) {
            val spuNum: Int = merchat.spuNum as Int
            binding.tvItems.text = "$spuNum Items"

            binding.tvItems.visibleOrGone(spuNum > 0) {}
            binding.div.visibleOrGone(merchat.subNums ?: 0 > 0 && spuNum > 0) {}
            binding.divide.visibleOrGone(merchat.subNums ?: 0 > 0 && spuNum > 0) {}
        }
        binding.ivDiscount.visibleOrGone(merchat.brandDiscount ?: 0 > 0) {}
        binding.tvDiscount.visibleOrGone(merchat.brandDiscount ?: 0 > 0) {
            setBackgroundResource(R.drawable.tag_store_discount)
            buildSpannableString {
                addText("Up To ") {
                    FontUtil.getTypeface(FontUtil.MONTSERRAT_MEDIUM)?.let {
                        setTypeface(it)
                    }
                }
                addText("${merchat.brandDiscount}%") {
                    setScale(1.2f)
                    FontUtil.getTypeface(FontUtil.MONTSERRAT_BOLD)?.let {
                        setTypeface(it)
                    }
                }
                addText(" Off") {
                    FontUtil.getTypeface(FontUtil.MONTSERRAT_MEDIUM)?.let {
                        setTypeface(it)
                    }
                }
            }
        }
        binding.groupPrds.visibleOrGone(merchat.productList?.isNotEmpty() == true) {
//            GlideUrl(merchat.productList!![0]?.productF?.mainImg ?: "",LazyHeaderFactoryaddHead())
            binding.imgPrd1.load(merchat.productList!![0]?.productF?.mainImg ?: "")
            binding.imgPrd1.setOnClickListener {
                toGoodsDetail(merchat.productList!![0]?.productF)
            }
            Glide.with(this).asBitmap().load(merchat.productList!![0]?.productF?.mainImg ?: "")
                .into(binding.imgPrd1)
            binding.imgPrd2.visibleOrGone(
                merchat.productList!!.size > 1,
                goneMode = View.INVISIBLE
            ) {
                load(merchat.productList!![1]?.productF?.mainImg ?: "")
                setOnClickListener {
                    toGoodsDetail(merchat.productList!![1]?.productF)
                }
            }
            binding.imgPrd3.visibleOrGone(
                merchat.productList!!.size > 2,
                goneMode = View.INVISIBLE
            ) {
                load(merchat.productList!![2]?.productF?.mainImg ?: "")
                setOnClickListener {
                    toGoodsDetail(merchat.productList!![2]?.productF)
                }
            }
            binding.imgPrd4.visibleOrGone(
                merchat.productList!!.size > 3,
                goneMode = View.INVISIBLE
            ) {
                load(merchat.productList!![3]?.productF?.mainImg ?: "")
                setOnClickListener {
                    toGoodsDetail(merchat.productList!![3]?.productF)
                }
            }

            merchat.productList?.getOrNull(0)?.productF?.run {
                binding.imgPrd1.trackData(
                    page = pageDef,
                    element = SpmElementDef.GoodStoreBodyProductClick,
                    params = SpmTrackHandler.trackProductMap(0, this)
                        .apply {
                            put("feedType", if (recommended) "recommend" else "")
                            put("brandName", merchat.name ?: "")
                            put("searchTerm", searchTerm)
                            put("searchType", searchType)
                        },
                    businessSuffixID = businessSuffixId(this)
                )
            }

            merchat.productList?.getOrNull(1)?.productF?.run {
                binding.imgPrd2.trackData(
                    page = pageDef,
                    element = SpmElementDef.GoodStoreBodyProductClick,
                    params = SpmTrackHandler.trackProductMap(1, this)
                        .apply {
                            put("feedType", if (recommended) "recommend" else "")
                            put("brandName", merchat.name ?: "")
                            put("searchTerm", searchTerm)
                            put("searchType", searchType)
                        },
                    businessSuffixID = businessSuffixId(this)
                )
            }

            merchat.productList?.getOrNull(2)?.productF?.run {
                binding.imgPrd3.trackData(
                    page = pageDef,
                    element = SpmElementDef.GoodStoreBodyProductClick,
                    params = SpmTrackHandler.trackProductMap(2, this)
                        .apply {
                            put("feedType", if (recommended) "recommend" else "")
                            put("brandName", merchat.name ?: "")
                            put("searchTerm", searchTerm)
                            put("searchType", searchType)
                        },
                    businessSuffixID = businessSuffixId(this)
                )
            }
            merchat.productList?.getOrNull(3)?.productF?.run {
                binding.imgPrd4.trackData(
                    page = pageDef,
                    element = SpmElementDef.GoodStoreBodyProductClick,
                    params = SpmTrackHandler.trackProductMap(3, this)
                        .apply {
                            put("feedType", if (recommended) "recommend" else "")
                            put("brandName", merchat.name ?: "")
                            put("searchTerm", searchTerm)
                            put("searchType", searchType)
                        },
                    businessSuffixID = businessSuffixId(this)
                )
            }
        }

        binding.btnFollow.run {
            if (merchat.hasSub) {
                text = string(com.starblink.basic.style.R.string.following)
                setTextColor(color(com.starblink.basic.style.R.color.gu_text_white_secondary))
                icon = null
                backgroundTintList =
                    ColorStateList.valueOf(color(com.starblink.basic.style.R.color.gu_black_07))
            } else {
                text = string(com.starblink.basic.style.R.string.follow)
                icon = RotateDrawable().apply {
                    drawable = ContextCompat.getDrawable(
                        itemView.context,
                        R.mipmap.icon_new_follow_1
                    )
                }
                setTextColor(color(com.starblink.basic.style.R.color.gu_text_primary))
                backgroundTintList =
                    ColorStateList.valueOf(color(com.starblink.basic.style.R.color.tag_yellow_1))
            }
            setOnClickListener {
                onFollowClick?.invoke(merchat, position)
            }

        }

        binding.btnFollow.trackData(
            page = pageDef,
            element = SpmElementDef.Element_33087,
            onlyHit = true,
            params = mapOf(
                "brandName" to (merchat.name ?: ""),
                "index" to if (recommended) recommendIndex.toString() else position.toString(),
                "feedType" to if (recommended) "recommend" else "",
                "searchType" to searchType,
                "searchTerm" to searchTerm,
                "result" to (if (merchat.hasSub) "0" else "1"),
            ),
            businessSuffixID = businessSuffixId(merchat)
        )

        itemView.setOnClickListener {
            navigationTo(RoutePage.Brand.BRAND_DETAIL) {
                withString(RoutePage.Brand.ARG_BRAND_ID, merchat.brandId.toString())
                withBoolean(RoutePage.Brand.ARG_IS_DISCOUNT_BRAND, merchat.brandDiscount != null)
            }
        }
    }

    private fun toGoodsDetail(product: ProductF?) {
        product?.id ?: return
        CommonRoute.startProductDetail(
            productId = product.productId ?: "",
            standardSpuIds = product.standardSpuIds ?: "",
            product
        )
    }


}

/**
 * 推荐店铺
 */
class BrandRecommendResultCell(
    pageDef: Int = SpmPageDef.SearchBrandPage,
    searchType: String = "normal",
    searchTerm: String = "",
    viewGroup: ViewGroup,
    onFollowClick: ((merchant: BrandVOF, position: Int) -> Unit)? = null
) :
    BaseVH<SearchBrandRecommendModel>(FrameLayout(viewGroup.context).apply {
        layoutParams = ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
    }) {

    private var pageDef: Int = 0

    var searchType: String = ""
    var searchTerm: String = ""

    val cell = BrandResultCell(
        CellSearchBrandBinding.inflate(
            itemView.inflater,
            itemView as ViewGroup,
            false
        ), true, searchType, searchTerm, pageDef, onFollowClick
    )

    init {
        (itemView as FrameLayout).addView(cell.itemView)
        this.pageDef = pageDef
        this.searchType = searchType
        this.searchTerm = searchTerm
    }


    override fun onBind(model: SearchBrandRecommendModel, position: Int) {
        val merchant = model.merchant
        cell.recommendIndex = model.index

        cell.onBind(model.merchant, position)
    }


}